package com.nfit.rabbitmq.consumer;

import com.rabbitmq.client.*;

/**
 * ClassName:FanoutConsumerB
 * Package:com.nfit.rabbitmq.consumer
 * Description
 *
 * @Author L
 * @Create 2024/11/22 8:35
 */
public class FanoutConsumerB {
    /**
     * 交换机
     */
    private static final String EXCHANGE_NAME = "test_queue";

    private static final String ROUTING_KEY = "test_b.queue";

    public static void main(String[] args) throws Exception {
        //初始化连接工厂，并指定rabbitmq的主机地址, 默认端口为5672
        //初始化链接工厂并设置rabbitmq的主机地址
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672); //通信接口,1572是rabbitmq端口
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        //创建连接对象，并使用连接对象构建一个消息通信的通道
        Connection conn = factory.newConnection();
        Channel channel = conn.createChannel();
        //声明Exchange，类型为fanout
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
        //声明queue
        channel.queueDeclare(ROUTING_KEY, false, false, false, null);
        //为queue和exchange绑定路由key，这里将路由key可设置为任意字符，通常设置为""
        channel.queueBind(ROUTING_KEY, EXCHANGE_NAME, "");
        //接收消息
        DeliverCallback callback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println("ConsumerB receive message: " + message);
        };
        channel.basicConsume(ROUTING_KEY, true, callback, consumerTag -> {});
    }
}
